<template>
   <div class="p-4">
      <BasicTable @register="registerTable" @fetch-success="onFetchSuccess" @row-click="rowClick" class="xl-w-3/4"
         style="float: left;">
         <template #toolbar>
            <el-button type="primary" @click="handleCreate">新增角色</el-button>
         </template>
         <template #enabled="{ record }">
            <el-switch v-model="record.state" inline-prompt active-text="激活" inactive-text="禁用" />
         </template>
         <template #roles="{ record }">
            <!-- <el-tag v-for="item in record.roles" :key="item.id" :type="getRoleType(item.level)" class="mr-1"
               effect="dark" round>
               {{ item.name }}
            </el-tag> -->
         </template>
         <template #action="{ record }">
            <TableAction :actions="[
               {
                  icon: 'note-edit-line|svg',
                  tooltip: '编辑角色资料',
                  color: '#409eff',
                  onClick: handleEdit.bind(null, record)
               },
               {
                  icon: 'delete-outlined|svg',
                  color: '#f56c6c',
                  tooltip: '删除此角色',
                  popConfirm: {
                     title: '是否确认删除',
                     okText: '确认',
                     cancelText: '取消',
                     confirm: handleDelete.bind(null, record)
                  }
               }
            ]" />
         </template>
      </BasicTable>
      <div class="content-full-height xl-w-1/4 inline" style="float: right;">

         <el-collapse v-model="activeNames" accordion>
            <el-collapse-item name="关联菜单">
               <template #title>
                  <div class="menu-tree-header">
                     关联菜单
                  </div>
               </template>
               <RelationTree class="bg-white" :data="menuTreeData" :default-checkedkeys="defaultCheckedMenukeys"
                  @check="checkMenu">
               </RelationTree>
               <el-button type="primary" @click="saveRoleAndMenus(currentRoleRow)">保存</el-button>
            </el-collapse-item>
            <el-collapse-item name="关联api">
               <template #title>
                  <div class="menu-tree-header">
                     关联api
                  </div>
               </template>
               <RelationTree class="bg-white" :data="apiData" :default-checkedkeys="defaultCheckedApikeys"
                  @check="checkApi">
               </RelationTree>
               <el-button type="primary" @click="saveRoleAndApis(currentRoleRow)">保存</el-button>
            </el-collapse-item>
         </el-collapse>

      </div>
   </div>
</template>

<script lang="ts" setup>
import { BasicTable, useTable, TableAction } from '@/components/Table'
import { getRoleListByPage, updateRoleAndApis, updateRoleAndMenus } from '@/api/system/role'
import { findAllApi } from '@/api/system/api'
import { columns, searchFormSchema } from './role.data';
import { ElMessage } from 'element-plus';
import { Recordable } from '/#/global';
import RelationTree from './relationTree.vue';
import { Ref, ref } from 'vue';
import { getMenuTree } from '@/api/system/menu'
import { TreeKey } from 'element-plus/es/components/tree-v2/src/types';
import { isEmpty } from '@/utils/is';

const [registerTable, { reload, updateTableDataRecord, deleteTableDataRecord }] = useTable({
   title: '角色列表',
   api: getRoleListByPage,
   rowKey: 'id',
   columns,
   formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
      // autoSubmitOnEnter: true
   },
   highlightCurrentRow: true,
   useSearchForm: true,
   showTableSetting: true,
   border: true,
   pagination: {
      style: {
         display: "flex",
         justifyContent: "flex-end",
         position: 'absolute',
         right: 'none',
         bottom: '40px',
      },
   },
   handleSearchInfoFn(info) {
      console.log('handleSearchInfoFn', info)
      return info
   },
   actionColumn: {
      id: 'action',
      width: 160,
      label: '操作',
      slots: { customRender: 'action' }
   }
})

const menuTreeData = ref([])
const apiData = ref([])
const defaultCheckedMenukeys = ref([])
const defaultCheckedApikeys = ref([])
const currentRoleRow = ref<Recordable>({})

// 菜单树
const res = await getMenuTree()
menuTreeData.value = res


const apiDataRes = await findAllApi()
apiData.value = apiDataRes




function onFetchSuccess(data: Recordable) {
   ElMessage({
      message: '加载表格数据成功',
      type: 'success',
   })
}

function handleCreate() {
   //   openModal(true, {
   //     isUpdate: false,
   //   });
}


async function handleDelete(record: Recordable) {
   //   await deleteUserById(record.id)
   deleteTableDataRecord(record.id)
   ElMessage({
      message: `删除角色${record.username}成功`,
      type: 'success',
   })
}
function handleEdit(record: Recordable) {
   //   openModal(true, {
   //     record,
   //     isUpdate: true,
   //   });
}

function rowClick(row: Recordable) {
    defaultCheckedMenukeys.value = []
     defaultCheckedApikeys.value = []
   if (row.menus) {
      defaultCheckedMenukeys.value = row.menus.filter((item: Recordable) => item.pid).map((item: Recordable) => item.id)
   }
   if (row.apis) {
      defaultCheckedApikeys.value = row.apis.map((item: Recordable) => item.id)
   }
   currentRoleRow.value = row
}

const saveRoleAndMenus = async (values: Recordable) => {
   console.log(values)
   if (!isEmpty(values)) {
      await updateRoleAndMenus(values)
      reload()
      ElMessage({
         message: `更新角色${values['name']}成功`,
         type: 'success',
      })
   } else {
      ElMessage({
         message: `请选择角色行`,
         type: 'warning',
      })
   }
}

const saveRoleAndApis = async (values: Recordable) => {
   console.log(values)
   if (!isEmpty(values)) {
      await updateRoleAndApis(values)
      reload()
      ElMessage({
         message: `更新角色${values['name']}成功`,
         type: 'success',
      })
   } else {
      ElMessage({
         message: `请选择角色行`,
         type: 'warning',
      })
   }
}


const activeNames = ref(['关联菜单'])

function checkMenu(menuIds: Ref<Array<TreeKey>>) {
   currentRoleRow.value.menuIds = menuIds.value
}
function checkApi(apiIds: Ref<Array<TreeKey>>) {
 currentRoleRow.value.apiIds = apiIds.value
}
</script>

<style lang="scss" setup>
.menu-tree-header {
   display: inline-flex;
   align-items: center;
   width: 90%;
   margin: 10px;
   justify-content: space-between;
}
</style>